#define NABTON_DATA 1
#define NABTON_DATA_ACK 2

#define ON_HB_VAL        2
#define ON_HB_UNIT       3
#define ON_STEPPER_DIR   4
#define ON_STEPPER_STEPS 5
#define ON_STEPPER_SPEED 6

#define MAX_SID 5
int nabton_hb = 2;
int nabton_hb_unit = 1; // 1=sec
int nabton_sid = 0;
int msg[100];
int on[100];
int value[100];
int sid[MAX_SID];
int sidHb[MAX_SID];
int sidHbUnit[MAX_SID];
int sidDelay[MAX_SID]; // Always in sec
int sidCountDown[MAX_SID];

unsigned long ttemp;
unsigned long time1, time2, data;


//=================================================
void recACK()
//=================================================
{
     int i,k,ndata,unit,indexSid,sidGeneric;
     float tempC;
     char buffer[50];
     String str;

     int nx = Serial.available();

     for(i=0;i<100;i++)on[i] = 0;
// Message received
//------------------------------------
  if (nx > 0) 
  {
     Serial.readBytes(buffer,nx);
     for(i=0;i<nx;i++)
     {
       msg[i] = (int)buffer[i]; 
     }
     str = String(nx);
       
     if(msg[0] == NABTON_DATA_ACK)
     {

       nabton_sid = msg[1] + msg[2]*256;

       indexSid = 0;
       for(i=1;i<MAX_SID;i++)
       {
        if(sid[i] == nabton_sid) indexSid = i; 
       }
       // sid exists!
       if(indexSid != 0)
       {
         k = 3;
         while(msg[k] != 0)
         {
           on[msg[k]] = 1;
           value[msg[k]] = msg[k+1];
           k = k + 2;
         }
         k = k-1;
         
         sidHb[indexSid]     = value[ON_HB_VAL];
         sidHbUnit[indexSid] = value[ON_HB_UNIT];
         if(sidHbUnit[indexSid] == 1) unit = 1; // sec
         if(sidHbUnit[indexSid] == 2) unit = 60; //minute
         if(sidHbUnit[indexSid] == 3) unit = 60*60; // hour
         if(sidHbUnit[indexSid] == 4) unit = 24*60*60; //24h
         ttemp = sidHb[indexSid]*unit;
         if(ttemp > 4000000000) ttemp = 4000000000;       
         sidDelay[indexSid] = ttemp;  
         sidCountDown[indexSid] = ttemp;
       } 
     }
  }
}
//======================================
void pulse()
//======================================
{ 
      time2 = time1;
      time1 = millis();
      data = time1 - time2;
      digitalWrite(7,HIGH);
      delay(2);
      digitalWrite(7,LOW);
      Serial.print(NABTON_DATA);
      Serial.print(" "); 
      Serial.print(sid[1]);
      Serial.print(" "); 
      Serial.print(data);
      Serial.print(";");
      recACK();
}
//======================================
void setup()
//======================================
{
  pinMode(7,   OUTPUT);
  Serial.begin(9600);
  attachInterrupt(0, pulse, FALLING);
  sid[1] = 5;
}

//======================================
void loop()
//======================================
{
  delay(1000);
}
